package com.misty.reflect;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class ConstructorTest {
    /**
     * 获得无参构造器
     */
    @Test
    public void demo1(){
        try {
            //获得类的字节码文件对应的对象
            Class class1 = Class.forName("com.imist.reflect.Person");
            //得到无参构造器
            Constructor constructor = class1.getConstructor();
            Person person = (Person) constructor.newInstance();//相当于Persion persion = new Persion();
            person.say();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获得有参数的构造方法
     */
    @Test
    public void demo2(){
        try {
            //获得类的字节码文件对应的对象
            Class class1 = Class.forName("com.imist.reflect.Person");
            //得到无参构造器
            Constructor constructor = class1.getConstructor(String.class,int.class);
            Person person = (Person) constructor.newInstance("iMist",23);//相当于Person person = new Person("iMist",23);
            person.say();
            System.out.println( person.toString());

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
